<template>
  <n-grid cols="1 s:1 m:1 l:4 xl:4 2xl:4" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formParams" :rules="rules" ref="formRef">
        <n-form-item label="小程序名称" path="zfb_name">
          <n-input v-model:value="formParams.zfb_name" placeholder="请输入小程序名称" />
        </n-form-item>

        <n-form-item label="小程序描述" path="zfb_desc">
          <n-input v-model:value="formParams.zfb_desc" placeholder="请输入小程序描述" />
        </n-form-item>

        <n-form-item label="小程序appid" path="zfb_appid">
          <n-input placeholder="请输入小程序appid" v-model:value="formParams.zfb_appid" />
        </n-form-item>

        <n-form-item label="小程序服务id" path="zfb_service_id">
          <n-input placeholder="请输入小程序服务id" v-model:value="formParams.zfb_service_id" />
        </n-form-item>

        <n-form-item label="支付宝私钥rsaPrivateKey" path="rsaPrivateKey">
          <n-upload
            :action="`${uploadUrl1}/api/common/upload`"
            @finish="handleFinishrsa"
            v-model:file-list="raskeyFileList"
            max="1"
            name='file'
          >
            <n-button>上传文件</n-button>
          </n-upload>
        </n-form-item>

        <n-form-item label="支付宝公钥alipayCertPublicKey证书" path="alipayCertPublicKey">
          <n-upload
            :action="`${uploadUrl1}/api/common/upload`"
            @finish="handleFinish"
            v-model:file-list="certFileList"
            max="1"
            name='file'
          >
            <n-button>上传文件</n-button>
          </n-upload>
        </n-form-item>

        <n-form-item label="公钥appCertPublicKey证书" path="appCertPublicKey">
          <n-upload
            :action="`${uploadUrl1}/api/common/upload`"
            @finish="handleFinishkey"
            v-model:file-list="keyFileList"
            max="1"
            name='file'
          >
            <n-button>上传文件</n-button>
          </n-upload>
        </n-form-item>

        <n-form-item label="根证书alipayRootCert证书" path="alipayRootCert">
          <n-upload
            :action="`${uploadUrl1}/api/common/upload`"
            @finish="handleFinishroot"
            v-model:file-list="rootFileList"
            max="1"
            name='file'
          >
            <n-button>上传文件</n-button>
          </n-upload>
        </n-form-item>

        <n-form-item label="Logo" path="zfb_image">
          <BasicUpload
              :action="`${uploadUrl1}/api/common/cosupdate`"
              :width="100"
              :height="100"
              name="file"
              @uploadChange="changeSitePicture"
              :max="1"
              :maxSize="10"
              v-model:value="zfb_image"
              helpText="单个文件不超过10MB，最多只能上传1个文件"
          />
        </n-form-item>

        <div>
          <n-space>
            <n-button type="primary" :loading="subLoading" @click="formSubmit">更新小程序信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { useMessage, FormRules } from 'naive-ui';
  import { webconfigEdit,webconfiginfo } from '@/api/webconfig/index';
  import { useGlobSetting } from '@/hooks/setting';
  import type { UploadFileInfo } from 'naive-ui'
  const globSetting = useGlobSetting();
  const { uploadUrl } = globSetting;
  const uploadUrl1 = uploadUrl;
  const zfb_image = ref([]);
  const certFileList = ref([{}]);
  const keyFileList = ref([{}]);
  const rootFileList = ref([{}]);
  const raskeyFileList = ref([{}]);
  
  const rules: FormRules = {
    
  };

  const defaultValueRef = () => ({
    zfb_name: '',
    zfb_desc: '',
    zfb_appid: '',
    zfb_service_id: '',
    zfb_image: '',
    alipayCertPublicKey: '',
    appCertPublicKey: '',
    alipayRootCert: '',
    rsaPrivateKey: '',
  });

  const message = useMessage();
  const formRef: any = ref(null);
  const subLoading = ref(false);
  const formParams = ref(defaultValueRef());

  const handleFinishrsa = ({
    file,
    event
  }: {
    file: UploadFileInfo
    event?: ProgressEvent
  }) => {
    let res = JSON.parse((event?.target as XMLHttpRequest).response);
    const ext = file.name.split('.')[1]
    file.name = `支付宝私钥rsaPrivateKey.${ext}`
    formParams.value.rsaPrivateKey = res.data.path;
    return file;
  }

  const handleFinish = ({
    file,
    event
  }: {
    file: UploadFileInfo
    event?: ProgressEvent
  }) => {
    let res = JSON.parse((event?.target as XMLHttpRequest).response);
    const ext = file.name.split('.')[1]
    file.name = `支付宝公钥alipayCertPublicKey.${ext}`
    formParams.value.alipayCertPublicKey = res.data.path;
    return file;
  }

  const handleFinishkey = ({
    file,
    event
  }: {
    file: UploadFileInfo
    event?: ProgressEvent
  }) => {
    let res = JSON.parse((event?.target as XMLHttpRequest).response);
    const ext = file.name.split('.')[1]
    file.name = `公钥appCertPublicKey.${ext}`
    formParams.value.appCertPublicKey = res.data.path;
    return file;
  }

  const handleFinishroot = ({
    file,
    event
  }: {
    file: UploadFileInfo
    event?: ProgressEvent
  }) => {
    let res = JSON.parse((event?.target as XMLHttpRequest).response);
    const ext = file.name.split('.')[1]
    file.name = `根证书alipayRootCert.${ext}`
    formParams.value.alipayRootCert = res.data.path;
    return file;
  }

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        formParams.value.zfb_image = zfb_image.value[0];
        webconfigEdit(formParams.value).then((_) => {
          message.success('更新成功');
        });
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  function getInfo() {
    webconfiginfo({}).then((res) => {
      const params = {
        zfb_name: res.zfb_name,
        zfb_desc: res.zfb_desc,
        zfb_appid: res.zfb_appid,
        zfb_service_id: res.zfb_service_id,
        rsaPrivateKey: res.rsaPrivateKey,
        alipayCertPublicKey: res.alipayCertPublicKey,
        appCertPublicKey: res.appCertPublicKey,
        alipayRootCert: res.alipayRootCert,
      };
      zfb_image.value = res.zfb_image;
      raskeyFileList.value = [];
      if(res.rsaPrivateKey != '' && res.rsaPrivateKey != null){
        raskeyFileList.value.push({
          id: 1,
          name: '支付宝私钥rsaPrivateKey.crt',
          status: 'finished',
        });
      }

      certFileList.value = [];
      if(res.alipayCertPublicKey != '' && res.alipayCertPublicKey != null){
        certFileList.value.push({
          id: 1,
          name: '支付宝公钥alipayCertPublicKey.crt',
          status: 'finished',
        });
      }
      
      keyFileList.value = [];
      if(res.appCertPublicKey != '' && res.appCertPublicKey != null){
        keyFileList.value.push({
          id: 1,
          name: '公钥appCertPublicKey.crt',
          status: 'finished',
        });
      }

      rootFileList.value = [];
      if(res.alipayRootCert != '' && res.alipayRootCert != null){
        rootFileList.value.push({
          id: 1,
          name: '根证书alipayRootCert.crt',
          status: 'finished',
        });
      }
      
      formParams.value = Object.assign(formParams.value, params);
    });
  }

  function changeSitePicture(file){
    zfb_image.value = file;
  }

  onMounted(async () => {
    getInfo();
  });
</script>
